package com.kerpow.KSheet;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.kerpow.KSheet.NoteListItem.OnNoteClickedHandler;
import com.kerpow.KSheet.NumberEntry.NumberEntryMode;
import com.kerpow.KSheet.NumberEntry.OnEntryListener;
import com.kerpow.KSheet.PowerView.OnPowerClickedHandler;
import com.kerpow.KSheet.character.CharacterAdapter;
import com.kerpow.KSheet.character.Power;
import com.kerpow.KSheet.character.CharacterAdapter.PowerSortMethod;
import com.kerpow.KSheet.character.Stat.StatType;

public class CharacterSheet extends Activity {

	private static final String CURRENT_POWER_POINTS = "Current Power Points";
	private static final String POWER_POINTS = "Power Points";
	private static final String TEMP_HITPOINTS = "Temporary Hit Points";
	private static final String HITPOINTS = "Hit Points";
	private static final String CURRENT_HITPOINTS= "Current Hit Points";
	private static final String SURGES = "Healing Surges";
	private static final String CURRENT_SURGES = "Current Healing Surges";
	private static final String ACTION_POINTS = "Action Points";
	
	private CharacterAdapter _db; 
	private long _characterID;
	private String _characterPath;
	
	private static final int MENU_SHORTREST = Menu.FIRST;
	private static final int MENU_MILESTONE = Menu.FIRST + 1;
	private static final int MENU_EXTENDEDREST = Menu.FIRST + 2;
	private static final int MENU_SHOWPOWERS = Menu.FIRST + 3;
	private static final int MENU_SETTINGS = Menu.FIRST + 4;
	
	
	private final int DLG_DETAIL_MENU = 0;
	private final int DLG_NUMBER_INPUT = 1;
	private final int DLG_UNUSED_POWER_CLICKED = 2;
	private final int DLG_USED_POWER_CLICKED = 3;
	private final int DLG_NOTE_MENU = 4;
	
	private PowerView _clickedPower;
	private CharacterNote _clickedNote;
	
	private EntryType _performingAction;
	private enum EntryType{
		damage,
		healing,
		healing_with_surge,
		temphp,
		lose_powerpoints,
		gain_powerpoints
	}
			
	private int _surgeValue;
		
	private View _details;
	private View _powers;
	private View _skills;
	private View _notes;
	private ImageView _detailstab;
	private ImageView _powerstab;
	private ImageView _skillstab;
	private ImageView _notestab;
	private LinearLayout _powerLayout;
	private LinearLayout _noteLayout;
	private Button _noteAddButton;
	private EditText _noteEdit;
	
	private boolean _updatingNote;
	private boolean _isPsionic = false;;
	
	private Cursor _skillsCursor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.charactersheet);
		
		_characterPath = (savedInstanceState == null) ? null: (String) savedInstanceState.getSerializable("path");
        if(_characterPath == null){
        	Bundle extras = getIntent().getExtras();
        	_characterPath = extras != null ? extras.getString("path") : null;
        }
        
        

		        
        LayoutInflater inflater = getLayoutInflater();

        //add search drawer
        ViewGroup vg = (ViewGroup)findViewById(R.id.content);
        _details = inflater.inflate(R.layout.viewdetails, null);
        vg.addView(_details);
        
        _powers = inflater.inflate(R.layout.viewpowers, null);
        vg.addView(_powers);
        _powerLayout = (LinearLayout) _powers.findViewById(R.id.powerslayout);
               
        _skills = inflater.inflate(R.layout.viewskills, null);
        vg.addView(_skills);
                
        _notes = inflater.inflate(R.layout.viewnotes, null);
        vg.addView(_notes);
        _noteLayout = (LinearLayout)_notes.findViewById(R.id.notelist);  
        _noteAddButton = (Button) _notes.findViewById(R.id.newnoteadd);
        _noteEdit = (EditText) _notes.findViewById(R.id.newnotebody);
        
        setupButtons();
        setupNotes();
        
        changePage(0);
	}

	@Override
	protected void onPause() {
		super.onPause();
		_db.close();
		_db = null;
	}

	@Override
	protected void onResume() {
		super.onResume();
		_db = new CharacterAdapter(this);
		_db.open();
		_characterID = _db.getCharacterID(_characterPath);
        _surgeValue = safeParseInt(_db.getStat(_characterID, HITPOINTS).Value) / 4;
        showName();
        showDynamicStats();
        showStaticStats();
        
        updatePowers();
        updateNotes();
		updateSkills();

		
		
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_SHORTREST, 0, R.string.menu_shortrest);
        menu.add(0, MENU_MILESTONE, 0, R.string.menu_milestone);
        menu.add(0, MENU_EXTENDEDREST, 0, R.string.menu_extendedrest);
        menu.add(0, MENU_SHOWPOWERS, 0, R.string.menu_showpowers);
        menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings);
       return true;
    }

    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
        case MENU_SHORTREST:
    		_db.setEncounterPowersUnused(_characterID);
    		_db.setStat(_characterID, TEMP_HITPOINTS, "0");
    		_db.setStat(_characterID, CURRENT_POWER_POINTS, _db.getStat(_characterID, POWER_POINTS).Value);
    		showDynamicStats();
    		updatePowers();
    		toast(R.string.toast_shortrest);
        	return true;
        case MENU_MILESTONE:
    		_db.setEncounterPowersUnused(_characterID);
    		_db.setStat(_characterID, TEMP_HITPOINTS, "0");
    		_db.setStat(_characterID, CURRENT_POWER_POINTS, _db.getStat(_characterID, POWER_POINTS).Value);
    		int ap = safeParseInt(_db.getStat(_characterID, ACTION_POINTS).Value)+1;
    		_db.setStat(_characterID, ACTION_POINTS, String.valueOf(ap));
    		showDynamicStats();
    		updatePowers();
    		toast(R.string.toast_milestone);
        	return true;
        case MENU_EXTENDEDREST:
        	_db.setPowersUnUsed(_characterID);
        	_db.setStat(_characterID, CURRENT_HITPOINTS, _db.getStat(_characterID, HITPOINTS).Value);
        	_db.setStat(_characterID, CURRENT_SURGES, _db.getStat(_characterID, SURGES).Value);
    		_db.setStat(_characterID, TEMP_HITPOINTS, "0");
    		_db.setStat(_characterID, ACTION_POINTS, "1");
    		_db.setStat(_characterID, CURRENT_POWER_POINTS, _db.getStat(_characterID, POWER_POINTS).Value);
        	showDynamicStats();
        	updatePowers();
        	toast(R.string.toast_extendedrest);
        	return true;
        case MENU_SHOWPOWERS:
        	_db.setPowersShown(_characterID);
        	updatePowers();
        	toast(R.string.toast_showpowers);
        	return true;
        case MENU_SETTINGS:
			Intent i = new Intent(this,Settings.class);
			startActivity(i);   	
        	return true;
       }

        return super.onOptionsItemSelected(item);
    }
	
    OnClickListener _detailClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(GlobalSettings.menuActivation == 0) showDialog(DLG_DETAIL_MENU);
		}
	};
	OnLongClickListener _detailLongClick = new OnLongClickListener() {
		
		@Override
		public boolean onLongClick(View v) {
			if(GlobalSettings.menuActivation == 1) showDialog(DLG_DETAIL_MENU);
			return true;
		}
	};
	    
	private void setupButtons(){
		
		View v = (View)findViewById(R.id.details_clickarea);
		v.setOnClickListener(_detailClick);
		v.setOnLongClickListener(_detailLongClick);
        
        
        _detailstab = (ImageView)findViewById(R.id.tab_details);
        _detailstab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changePage(0);
			}
		});
        
        _powerstab = (ImageView)findViewById(R.id.tab_powers);
        _powerstab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changePage(1);
			}
		});
        
        _skillstab = (ImageView)findViewById(R.id.tab_skills);
        _skillstab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changePage(2);
			}
		});

        _notestab = (ImageView)findViewById(R.id.tab_notes);
        _notestab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changePage(3);
			}
		});

	}
	
	private void changePage(int pageID){
		_detailstab.setImageResource(R.drawable.details);
		_powerstab.setImageResource(R.drawable.power);
		_skillstab.setImageResource(R.drawable.skills);
		_notestab.setImageResource(R.drawable.notes);
		_details.setVisibility(View.GONE);
		_powers.setVisibility(View.GONE);
		_skills.setVisibility(View.GONE);
		_notes.setVisibility(View.GONE);
		
		switch(pageID){
		case 0:
			_detailstab.setImageResource(R.drawable.details_clicked);
			_details.setVisibility(View.VISIBLE);
			break;
		case 1:
			_powerstab.setImageResource(R.drawable.power_clicked);
			_powers.setVisibility(View.VISIBLE);
			break;
		case 2:
			_skillstab.setImageResource(R.drawable.skills_clicked);
			_skills.setVisibility(View.VISIBLE);
			break;
		case 3:
			_notestab.setImageResource(R.drawable.notes_clicked);
			_notes.setVisibility(View.VISIBLE);
			break;
		}
	}
	
	private void toast(int res){
		Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
	}
	private void toast(String msg){
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Log.i("kerpow","Creating dialog " + id);
		boolean usedPowerClicked = true;
		switch(id){
		case DLG_NUMBER_INPUT:
			return new NumberEntry(this, new  OnEntryListener() {
				
				@Override
				public void OnEntry(int value, boolean addSurgeValue, boolean loseSurge) {
					int temp, hp, maxhp, pp, maxpp;
					
					switch(_performingAction){
					case damage:
						
						temp = safeParseInt(_db.getStat(_characterID, TEMP_HITPOINTS).Value);
						hp = safeParseInt(_db.getStat(_characterID, CURRENT_HITPOINTS).Value);
						
						temp -= value;
						if(temp < 0){
							value = Math.abs(temp);
							hp -= value;
							temp = 0;
						}
						
						_db.setStat(_characterID, TEMP_HITPOINTS, String.valueOf(temp));
						_db.setStat(_characterID, CURRENT_HITPOINTS, String.valueOf(hp));
						
						toast("You took " + value + " damage");
						showDynamicStats();
						break;
					case healing:
						int surges = safeParseInt(_db.getStat(_characterID, CURRENT_SURGES).Value);
						if(!loseSurge || surges > 0){
							maxhp = safeParseInt(_db.getStat(_characterID, HITPOINTS).Value);
							hp = safeParseInt(_db.getStat(_characterID, CURRENT_HITPOINTS).Value);
							
							if(addSurgeValue) value += _surgeValue;
	
							if(hp + value > maxhp ){
								value = maxhp - hp;
							}
							hp += value;
	
							_db.setStat(_characterID, CURRENT_HITPOINTS, String.valueOf(hp));
							
							if(loseSurge){
								surges--;
								_db.setStat(_characterID, CURRENT_SURGES, String.valueOf(surges));
								toast("You spent a surge and healed " + value + " hit points");
							}else
								toast("You healed " + value + " hit points");
							
							showDynamicStats();
							break;
						}else
							toast("You don't have a surge to spend");
						
					case temphp:
						
						temp = safeParseInt(_db.getStat(_characterID, TEMP_HITPOINTS).Value);
						if(temp > value)
							value = 0;
						else
							temp = value;
						
						_db.setStat(_characterID, TEMP_HITPOINTS, String.valueOf(temp));
						toast("You gained " + value + " temporary hit points");
						showDynamicStats();
						break;
					case lose_powerpoints:
						pp = safeParseInt(_db.getStat(_characterID, CURRENT_POWER_POINTS).Value);
						
						if(pp - value < 0){
							value = value - pp;
							
						}
						pp -= value;
						_db.setStat(_characterID, CURRENT_POWER_POINTS, String.valueOf(pp));
						
						toast("You spent " + value + " power points");
						showDynamicStats();
						break;
					case gain_powerpoints:
						pp = safeParseInt(_db.getStat(_characterID, CURRENT_POWER_POINTS).Value);
						maxpp = safeParseInt(_db.getStat(_characterID, POWER_POINTS).Value);
						
						if(pp + value > maxpp){
							value = maxpp - pp;
							pp = maxpp;
						}else
							pp += value;
						
						_db.setStat(_characterID, CURRENT_POWER_POINTS, String.valueOf(pp));
						
						toast("You gained " + value + " power points");
						showDynamicStats();
						break;
					}
					
				}
			});	
		case DLG_DETAIL_MENU:
		{
			final CharSequence[] items = {"Take Damage", "Receive Healing", "Gain Temp Hit Points", 
					"Lose Healing Surge", "Lose Action Point",
					"Gain Healing Surge", "Gain Action Point"};

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			//builder.setTitle("What's happening?");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				
				
			    public void onClick(DialogInterface dialog, int item) {
			    	int value, max;
			    	switch(item){
			    	case 0: _performingAction = EntryType.damage; showDialog(DLG_NUMBER_INPUT); break;
			    	case 1: _performingAction = EntryType.healing; showDialog(DLG_NUMBER_INPUT); break;
			    	case 2: _performingAction = EntryType.temphp; showDialog(DLG_NUMBER_INPUT); break;
			    	case 5: 
			    		value = safeParseInt(_db.getStat(_characterID, CURRENT_SURGES).Value);
			    		max = safeParseInt(_db.getStat(_characterID, SURGES).Value);
			    		value ++;
			    		if(value > max ) break;
			    		_db.setStat(_characterID, CURRENT_SURGES, String.valueOf(value));
						toast("You gained a healing surge");
						showDynamicStats();
			    		break;
			    	case 3: 
			    		value = safeParseInt(_db.getStat(_characterID, CURRENT_SURGES).Value);
			    		value --;
			    		if(value < 0) break;
			    		_db.setStat(_characterID, CURRENT_SURGES, String.valueOf(value));
						toast("You lost a healing surge");
						showDynamicStats();
			    		break;
			    	case 6: 
			    		value = safeParseInt(_db.getStat(_characterID, ACTION_POINTS).Value);
			    		value ++;
			    		_db.setStat(_characterID, ACTION_POINTS, String.valueOf(value));
						toast("You gained an action point");
						showDynamicStats();
			    		break;
			    	case 4: 
			    		value = safeParseInt(_db.getStat(_characterID, ACTION_POINTS).Value);
			    		value --;
			    		if(value < 0) break;
			    		_db.setStat(_characterID, ACTION_POINTS, String.valueOf(value));
						toast("You lost an action point");
						showDynamicStats();
			    		break;
			    	}
			        //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
			    }
			});
			AlertDialog alert = builder.create();
			return alert;
		}
		case DLG_UNUSED_POWER_CLICKED:
			usedPowerClicked = false;
		case DLG_USED_POWER_CLICKED:
			{
				final CharSequence[] items = {"Use Power", "Hide Power"};
				
				if(usedPowerClicked)			
					items[0] = "Refresh Power";
				
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				
				builder.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						PowerClickedDialogHandler(which);
					}
				});
				AlertDialog alert = builder.create();
				return alert;
			}
		case DLG_NOTE_MENU:
			{
				final CharSequence[] items = {"Edit Note", "Delete note"};
							
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				
				builder.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which==0){
							_noteAddButton.setText(R.string.note_buttonupdate);
							_updatingNote = true;
							_noteEdit.setText(_clickedNote.Note);
						}else{
							_db.deleteNote(_clickedNote.ID);
							toast(R.string.toast_notedeleted);
						}
						updateNotes();			
						
					}
				});
				AlertDialog alert = builder.create();
				return alert;
			}
		}
		
		return super.onCreateDialog(id);
	}

	private void PowerClickedDialogHandler(int itemClicked){
		switch(itemClicked){
		case 0:
			if(_isPsionic && _clickedPower.isAugmentable()){
				_performingAction = EntryType.lose_powerpoints;
				showDialog(DLG_NUMBER_INPUT);
			}
			if(!_clickedPower.isAtWill()){ //can't mark at-wills as used

				_db.setPowerUsed(_clickedPower.getPowerID(), !_clickedPower.isUsed());
				updatePowers();
			}
			break;
		case 1:
			_db.setPowerHidden(_clickedPower.getPowerID());
			updatePowers();
			break;
		}
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		
		if(id == DLG_NUMBER_INPUT){
			NumberEntry n = (NumberEntry)dialog;
			if(_performingAction!=null){
				switch(_performingAction){
				case damage: n.setup(NumberEntryMode.Damage); break;
				case healing: n.setup(NumberEntryMode.Healing); break;
				case temphp:n.setup(NumberEntryMode.TempHP); break;
				case gain_powerpoints: n.setup(NumberEntryMode.GainPowerPoints); break;
				case lose_powerpoints: n.setup(NumberEntryMode.LosePowerPoints); break;
				}	
			}
		}

		super.onPrepareDialog(id, dialog);
	}


	private void showStaticStats(){
		StatView sv;
		String s;
		
		sv = (StatView)findViewById(R.id.details_armorclass);
		s = _db.getStat(_characterID, "Armor Class").Value;
		sv.setValue(s);
		
		sv = (StatView)findViewById(R.id.details_fortitude);
		s = _db.getStat(_characterID, "Fortitude").Value;
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_reflex);
		s = _db.getStat(_characterID, "Reflex").Value;
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_will);
		s = _db.getStat(_characterID, "Will").Value;
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_strength);
		s = formatAbility(_db.getStat(_characterID, "Strength").Value);
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_constitution);
		s = formatAbility(_db.getStat(_characterID, "Constitution").Value);
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_dexterity);
		s = formatAbility(_db.getStat(_characterID, "Dexterity").Value);
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_intellect);
		s = formatAbility(_db.getStat(_characterID, "Intelligence").Value);
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_wisdom);
		s = formatAbility(_db.getStat(_characterID, "Wisdom").Value);
		sv.setValue(s);
		
		sv = (StatView)findViewById(R.id.details_charisma);
		s = formatAbility(_db.getStat(_characterID, "Charisma").Value);
		sv.setValue(s);

		sv = (StatView)findViewById(R.id.details_speed);
		s = _db.getStat(_characterID, "Speed").Value;
		sv.setValue(s);
		
		sv = (StatView)findViewById(R.id.details_initiative);
		s = _db.getStat(_characterID, "Initiative").Value;
		sv.setValue(s);
		
		sv = (StatView)findViewById(R.id.details_passivei);
		s = _db.getStat(_characterID, "Passive Insight").Value;
		sv.setValue(s);
		
		sv = (StatView)findViewById(R.id.details_passivep);
		s = _db.getStat(_characterID, "Passive Perception").Value;
		sv.setValue(s);
		
		sv = (StatView)findViewById(R.id.details_surgevalue);
		sv.setValue(String.valueOf(_surgeValue));
		
	}
	
	private void showName(){
		String details = _db.getStat(_characterID, "Name").Value;
		details += " (LVL ";
		details += _db.getStat(_characterID, "Level").Value;
		details += ")";
		
		TextView t = (TextView)findViewById(R.id.details_details);
		t.setText(details);
		
	}
	
	private void showDynamicStats(){
		StatView sv;
		
		String hp, chp, surges, csurges, ap, thp, pp, cpp;
		
		hp = _db.getStat(_characterID, HITPOINTS).Value;
		chp = _db.getStat(_characterID, CURRENT_HITPOINTS).Value;
		surges = _db.getStat(_characterID, SURGES).Value;
		csurges = _db.getStat(_characterID, CURRENT_SURGES).Value;
		ap = _db.getStat(_characterID, ACTION_POINTS).Value;
		thp = _db.getStat(_characterID, TEMP_HITPOINTS).Value;
		pp = _db.getStat(_characterID, POWER_POINTS).Value;
		cpp = _db.getStat(_characterID, CURRENT_POWER_POINTS).Value;
		
		sv = (StatView)findViewById(R.id.details_hitpoints);
		sv.setValue(chp + " / " + hp);
		
		sv = (StatView)findViewById(R.id.details_surges);
		sv.setValue(csurges + " / " + surges);
		
		sv = (StatView)findViewById(R.id.details_actionpoints);
		sv.setValue(ap);
		
		sv = (StatView)findViewById(R.id.details_temphitpoints);
		sv.setValue(thp);
		
		if(!pp.contains("-")){
			_isPsionic = true;
			sv = (StatView)findViewById(R.id.details_powerpoints);
			sv.setVisibility(View.VISIBLE);
			sv.setValue(cpp + " / " + pp);
		}
	}
		
    private void updatePowers(){
        Cursor c = _db.fetchPowers(_characterID,PowerSortMethod.Action);
        
        OnPowerClickedHandler clicked = new OnPowerClickedHandler() {

			@Override
			public void OnPowerClick(PowerView power) {
				if(GlobalSettings.menuActivation == 0) showPowerMenu(power);
			}

			@Override
			public void OnPowerLongClick(PowerView power) {
				if(GlobalSettings.menuActivation == 1) showPowerMenu(power);
			}
		};
        		
        _powerLayout.removeAllViews();
        if(c.moveToFirst()){
        	do{
        		Power p = Power.from(c);
                PowerView pv = new PowerView(this,p,clicked); 
                _powerLayout.addView(pv);
                
        	}while(c.moveToNext());
        }
        c.close();
    }
    
    private void showPowerMenu(PowerView p){
		_clickedPower = p;
		if(_clickedPower.isUsed())
			showDialog(DLG_USED_POWER_CLICKED);
		else
			showDialog(DLG_UNUSED_POWER_CLICKED);
    }
    
    
	private void updateSkills(){
		
		_skillsCursor = _db.fetchStats(_characterID, StatType.skill);
		
		startManagingCursor(_skillsCursor);
		
		// Create an array to specify the fields we want to display in the list 
		String[] from = new String[]{CharacterAdapter.FIELD_STATS_NAME, CharacterAdapter.FIELD_STATS_VALUE};
		
		// and an array of the fields we want to bind those fields to (in this case just text1)
		int[] to = new int[]{R.id.skill_row_name, R.id.skill_row_value};
		
		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter skills = 
		    new SimpleCursorAdapter(this, R.layout.skill_row, _skillsCursor, from, to);
		
		ListView lv = (ListView)findViewById(R.id.skills_list);
		lv.setAdapter(skills);
	}
	private String formatAbility(String ability){
		int val = safeParseInt(ability);
		val -= 10;
		val /= 2;
		return ability + " (" + val + ")";
	}
	
	private void setupNotes(){
		
		Button b = (Button) _notes.findViewById(R.id.newnotescan);
		b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		        startActivityForResult(intent, 0);
			}
		});
		
		_noteAddButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				_noteAddButton.setText(R.string.note_buttonadd);
				if(_updatingNote){
					_db.updateNote(_clickedNote.ID, _noteEdit.getText().toString());
					toast(R.string.toast_noteupdated);
				}else{
					_db.createNote(_characterID, _noteEdit.getText().toString());
					toast(R.string.toast_noteadded);
				}
				_updatingNote = false; 
				_noteEdit.setText("");
				updateNotes();
				
			}
		});
	}
	
	private void updateNotes(){
        OnNoteClickedHandler eventHandler = new OnNoteClickedHandler() {

			@Override
			public void OnNoteClick(CharacterNote n) {
				
				if(GlobalSettings.menuActivation == 0) {
					_clickedNote = n;
					showDialog(DLG_NOTE_MENU);
				}
			}

			@Override
			public void OnNoteLongClick(CharacterNote n) {
				
				if(GlobalSettings.menuActivation == 1) {
					_clickedNote = n;
					showDialog(DLG_NOTE_MENU);
				}			
			}
		};
		
		_noteLayout.removeAllViews();
		ArrayList<CharacterNote> notes = _db.reviewNotes(_characterID);
		for(CharacterNote note : notes){
			NoteListItem nli = new NoteListItem(this, note, eventHandler);
			_noteLayout.addView(nli);
		}
		
		//create feats note
		addSpecialNote("Feats", StatType.feat);
		addSpecialNote("Racial Traits", StatType.racialtrait);
		addSpecialNote("Class Features", StatType.classfeature);


		
		
	}
	
	private void addSpecialNote(String title, StatType type){
		StringBuilder notebuilder = new StringBuilder();
		String notebody;
		Cursor c = _db.fetchStats(_characterID, type);
		int id = c.getColumnIndex(CharacterAdapter.FIELD_STATS_NAME);
		
		if(c.moveToFirst())
			do{
				notebuilder.append(c.getString(id));
				notebuilder.append(", ");
			}while(c.moveToNext());
		
		if(notebuilder.length() > 2)
			notebody = notebuilder.substring(0, notebuilder.length() -2);
		else
			notebody= "Reload your character to use this feature.";

		NoteListItem nli = new NoteListItem(this, new CharacterNote(_characterID,notebody,title), null);
		_noteLayout.addView(nli);
	}
	
	private int safeParseInt(String stat){
		try{
			return Integer.parseInt(stat);
		}catch(Exception ex){
			return 0;
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
	    if (requestCode == 0) {
	        if (resultCode == RESULT_OK) {
	            String contents = intent.getStringExtra("SCAN_RESULT");
	            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
	            Log.i("kerpow","scan format " + format);
	            Log.i("kerpow","scan contents " + contents);
	            _noteEdit.setText(contents);
	        } else if (resultCode == RESULT_CANCELED) {
	            // Handle cancel
	        }
	    }
	}
}
